
import { ref, computed, onMounted, onUnmounted } from 'vue'

export interface ResponsiveLayoutConfig {
  defItemMinWidth :number // 默认最小宽度
  defaultRows?: number // 默认显示行数
  gap: number // 间隔
}

export interface ResponsiveLayoutResult {
  containerWidth: Ref<number>
  currentBreakpoint: ComputedRef<string>
  itemsPerRow: ComputedRef<number>
  calculatePageSize: (rows?: number) => number
  calculateItemsPerRow: (containerWidth: number) => number
}

export function responsiveGrid(
  containerRef: Ref<HTMLElement | null>,
  itemMinWidth: number,
  gap: number,
): ResponsiveLayoutResult {
  const containerWidth = ref(0)
  
  // 默认配置
  const defaultConfig: ResponsiveLayoutConfig = {
    defItemMinWidth:200,
    defaultRows: 3,
    gap:10,
  }
  
  const mergedConfig = { ...defaultConfig, ...{defItemMinWidth:itemMinWidth,gap} }
  

  
  // 计算每行显示数量
  const itemsPerRow = computed(() => {
    return Math.floor((containerWidth.value ) / (mergedConfig.defItemMinWidth + mergedConfig.gap)) || 1
  })
 
  
  // 计算每页显示数量（行数的整数倍）
  const calculatePageSize = (rows?: number): number => {
    const rowCount = rows || mergedConfig.defaultRows || 3
    return itemsPerRow.value * rowCount
  }
  

  
  // 更新容器宽度
  const updateContainerWidth = () => {
    if (containerRef.value) {
      containerWidth.value = containerRef.value.clientWidth
    }
  }
  
  // 防抖resize处理
  let resizeTimer: number | null = null
  const handleResize = () => {
    if (resizeTimer) {
      clearTimeout(resizeTimer)
    }
    resizeTimer = window.setTimeout(() => {
      updateContainerWidth()
    }, 100)
  }
  
  onMounted(() => {
    updateContainerWidth()
    window.addEventListener('resize', handleResize)
  })
  
  onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
    if (resizeTimer) {
      clearTimeout(resizeTimer)
    }
  })
  
  return {
    containerWidth,
    itemsPerRow,
    calculatePageSize,
  }
}